package md.NJavaBase;

import java.util.ArrayList;

public class LoaderList  {

    //注册一个广告
    public void RegAD(ILoader loader)
    {
        int  priority = loader.getPriority();
        if(
                m_LoaderList.size()==0||//列表是空的
                        ((ILoader)m_LoaderList.get(m_LoaderList.size()-1)).getPriority()>priority//列表末尾广告优先级高于新广告
        ) {
            //追加到末尾
            m_LoaderList.add( loader );
        }
        else{
            //寻找一个插入位置
            int i;
            for(i=m_LoaderList.size()-1;i>=0;i--)
            {
                ILoader curr = (ILoader)m_LoaderList.get(i);
                if(curr.getPriority()>=priority) break;
            }

            //插入新的广告
            m_LoaderList.add(i+1,loader);
        }
    }


    //统计处于某个状态的loader总数
    public  int getLoaderCount(AdState st)
    {
        int count = 0;
        for(int i=0;i<m_LoaderList.size();i++)
        {
            ILoader curr = (ILoader)m_LoaderList.get(i);
            if(curr.getState()==st) count++;
        }
        return count;
    }

    //根据状态获取一个loader,按照优先级
    public  ILoader getLoader( AdState st)
    {
        if(m_LoaderList.size()==0) return null;//无广告

        int idx = m_idx;
        int count = 0;
        do{
            ILoader curr = (ILoader)m_LoaderList.get(idx);
            if(curr.getState() == st)  return curr;
            idx = nextIdx(idx);
        }while (++count<m_LoaderList.size());

        return null;
    }

    //获取一个loader的索引号
    public int getLoaderIdx(ILoader loader)
    {
        for(int i=0;i<m_LoaderList.size();i++)
        {
            ILoader curr = (ILoader)m_LoaderList.get(i);
            if(curr==loader) return i;
        }
        return 0;
    }

    //移动当前广告指针
    public void moveIdx(int idx)
    {
        m_idx = nextIdx(idx);
    }

    //计算某个索引的下一个索引，并返回 环形
    public int nextIdx(int idx)
    {
        idx++;
        if(idx>=m_LoaderList.size()) idx = 0;
        return idx;
    }

    public int size()
    {
        return m_LoaderList.size();
    }

    public ILoader get(int i)
    {
        return (ILoader)m_LoaderList.get(i);
    }

    public int getIdx(){return m_idx;}


    int m_idx = 0;//当前预装广告位置
    ArrayList m_LoaderList = new ArrayList();
}
